


#include <map>
#include <ostream>
#include <string>
#include <iostream>
#include <string.h>

#include "sum.h"

using namespace std;

DataSum::DataSum(const Position &pos, const CALC_TYPE ct)
:m_mapPosition(pos),m_eCalcType(ct),m_nMaxKeyLength(0)
{

}

DataSum::~DataSum(void)
{
	for(map<string, result_t*>::iterator iter = m_mapKeySum.begin();
		iter != m_mapKeySum.end();
		++iter)
	{
		delete [] iter->second;
	}
}

void DataSum::add(const string &key, const int index, const long value)
{
	const int npos = m_mapPosition.pos(index);
	if(npos == -1)
		return;

	if(m_mapKeySum.find(key) == m_mapKeySum.end())
	{
		result_t* pLong = new result_t[m_mapPosition.size()];
		//memset(pLong, 0, sizeof(result_t) * m_mapPosition.size());
		m_mapKeySum[key] = pLong;
	}

	switch(m_eCalcType)
	{
		case CALC_MAX:
			if(m_mapKeySum[key][npos].nflag == 0)
				m_mapKeySum[key][npos].retval = value;	
			else
				m_mapKeySum[key][npos].retval = max(m_mapKeySum[key][npos].retval, value);
			++m_mapKeySum[key][npos].nflag;
			break;
		case CALC_MIN:
			if(m_mapKeySum[key][npos].nflag == 0)
				m_mapKeySum[key][npos].retval = value;
			else
				m_mapKeySum[key][npos].retval = min(m_mapKeySum[key][npos].retval, value);
			++m_mapKeySum[key][npos].nflag;
			break;
		case CALC_AVG:
		case CALC_SUM:
		default:
			m_mapKeySum[key][npos].retval += value;
			++m_mapKeySum[key][npos].nflag;
			break;
	}
	m_nMaxKeyLength = max(m_nMaxKeyLength, (int)key.length());
}

const int DataSum::GetMaxKeyLength(void) const
{
	return m_nMaxKeyLength;
}

const map<string,result_t*>& DataSum::GetData(void) const
{
	return m_mapKeySum;
}

const CALC_TYPE DataSum::GetCalcType(void) const
{
	return m_eCalcType;
}




#ifdef TEST_SUM

int main()
{
	Position pos0;
	for(int i = 1; i < 10; i+=2)
		pos0.add(i);

	DataSum  ds(pos0);
	string strKey = "henry";
	for(int i = 0; i < 11; ++i)
		ds.add(strKey, i, 1000*i);

	Output *csv_output = new CSVOutput(pos0.size());
	ds.flush(*csv_output);

	return 0;
}


/*
*/
#endif
